package com.pig4cloud.pig.ads.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.api.client.util.Lists;
import com.pig4cloud.pig.ads.main3399.mapper.TtAppManagementMapper;
import com.pig4cloud.pig.ads.service.AdvService;
import com.pig4cloud.pig.ads.service.TtAccesstokenService;
import com.pig4cloud.pig.ads.service.TtAppManagementService;
import com.pig4cloud.pig.ads.utils.OEHttpUtils;
import com.pig4cloud.pig.api.entity.Advertising;
import com.pig4cloud.pig.api.entity.ResponseBean;
import com.pig4cloud.pig.api.entity.TtAccesstoken;
import com.pig4cloud.pig.api.entity.TtAppManagement;
import com.pig4cloud.pig.common.core.constant.enums.PlatformTypeEnum;
import com.xxl.job.core.log.XxlJobLogger;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author cx
 * @version 1.0.0
 * @ClassName TtAppManagementServiceImpl.java
 * @createTime 2021年08月04日 16:56:00
 */
@Log4j2
@Service
@RequiredArgsConstructor
public class TtAppManagementServiceImpl extends ServiceImpl<TtAppManagementMapper, TtAppManagement> implements TtAppManagementService {

	private final AdvService advService;

	private final TtAccesstokenService ttAccesstokenService;

	@Override
	public void getAppManagement(JSONObject param) {
		XxlJobLogger.log("-----------------查询头条应用信息开始---------------------");
		long start = System.currentTimeMillis();
		// 获取广告账户信息
		LambdaQueryWrapper<Advertising> query = new LambdaQueryWrapper<>();
		query.and(wrapper -> wrapper.eq(Advertising::getDeleted, 0));
		query.and(wrapper -> wrapper.eq(Advertising::getPlatformId, PlatformTypeEnum.TT.getValue()));
		List<Advertising> advertisingList = advService.list(query);
		// 获取token
		List<TtAccesstoken> ttAccessTokenList = ttAccesstokenService.list();
		Map<String,String> tokenMap = ttAccessTokenList.stream().collect(Collectors.toMap(TtAccesstoken::getAdAccount,TtAccesstoken::getAccessToken));

		// 类型:(CREATE_ONLY:广告主创建的应用,SHARED_ONLY:被共享的应用)
		String[] searchTypes = new String[]{"CREATE_ONLY", "SHARED_ONLY"};

		final LocalDate currentDate = LocalDate.now();
		String startDateStr = param.getString("startDate");
		startDateStr = StringUtils.isBlank(startDateStr) ? currentDate.minusDays(1).format(DateTimeFormatter.ISO_LOCAL_DATE) : startDateStr;
		String endDateStr = param.getString("endDate");
		endDateStr = StringUtils.isBlank(endDateStr) ? currentDate.format(DateTimeFormatter.ISO_LOCAL_DATE) : endDateStr;
		// 获取searchType 默认查询广告主创建的应用
		String searchType = StringUtils.defaultIfBlank(param.getString("searchType"),"CREATE_ONLY");

		XxlJobLogger.log("执行时间:{}", startDateStr.concat(" ~ ").concat(endDateStr));
		// 获取数据已经存在的应用
		List<TtAppManagement> appManagementDb = this.list(Wrappers.<TtAppManagement>query().lambda()
				.eq(TtAppManagement::getSearchType, searchType)
				.eq(TtAppManagement::getIsDeleted, 0));

		List<TtAppManagement> insertList = Lists.newArrayList();
		for (Advertising advertising : advertisingList) {
			// 待广告账户很多时可以按500分页延迟查询
			String advertiserId = advertising.getAdvertiserId();
			String accessToken = tokenMap.get(advertising.getHousekeeper());
			if (StringUtils.isNotBlank(accessToken)) {
				List<TtAppManagement> appManagementList = this.getTtAppManagement(advertiserId, searchType, accessToken, startDateStr, endDateStr);
				if (CollectionUtils.isNotEmpty(appManagementList)) {
					for (TtAppManagement appManagement : appManagementList) {
						List<TtAppManagement> appManagements = appManagementDb.stream().filter(v ->
								v.getAppCloudId().equals(appManagement.getAppCloudId())
										&& v.getAdvertiserId().equals(advertiserId)
										&& v.getSearchType().equals(searchType)).collect(Collectors.toList());
						if (CollectionUtils.isEmpty(appManagements)) {
							insertList.add(appManagement);
							XxlJobLogger.log("新数据--> appId:{}, appName:{},accountId:{},searchType:{}",
									appManagement.getAppCloudId(),appManagement.getAppName(),advertiserId,appManagement.getSearchType());
						}
					}
				}
			}
		}
		if (CollectionUtils.isNotEmpty(insertList)) {
			// 批量插入数据
			this.saveBatch(insertList);
			XxlJobLogger.log("批量插入数据 {} 条", insertList.size());
		} else {
			XxlJobLogger.log("无数据插入");
		}
		long end = System.currentTimeMillis();
		XxlJobLogger.log("-----------------查询头条应用信息结束，耗时：" + (end - start) / 1000 + "秒---------------------");
	}

	public List<TtAppManagement> getTtAppManagement(String advertiserId, String searchType, String accessToken, String startDateStr, String endDateStr) {
		String url = "https://ad.oceanengine.com/open_api/2/tools/app_management/app/get/";
		List<TtAppManagement> appManagementList = Lists.newArrayList();
		int page = 1;
		while (true) {
			try {
				Map<String, Object> data = new HashMap<String, Object>();
				data.put("advertiser_id", advertiserId);
				data.put("search_type", searchType);
				data.put("status", "ENABLE");
				//统一按发布时间筛选
				data.put("publish_time", new HashMap<String, String>() {{
					put("start_time", startDateStr);
					put("end_time", endDateStr);
				}});

//				// 按创建时间获取会导致当天创建，过几天分享给其他账户，而创建时间不会变。从而导致被分享者获取不到应用。
//				// 创建者按创建时间获取
//				if ("CREATE_ONLY".equals(searchType)) {
//					//按创建时间获取、因为有过审的时间，会导致获取不到创建者的应用。修改为更新时间
//					data.put("update_time", new HashMap<String, String>() {{
//						put("start_time", startDateStr);
//						put("end_time", endDateStr);
//					}});
//				} else {
//					data.put("publish_time", new HashMap<String, String>() {{
//						put("start_time", startDateStr);
//						put("end_time", endDateStr);
//					}});
//				}
				data.put("page", page);
				data.put("page_size", 100);
				//调第三方平台（头条）接口
				String resultStr = OEHttpUtils.doGet(url, data, accessToken);
				ResponseBean resBean = JSON.parseObject(resultStr, ResponseBean.class);
				if (resBean != null && "0".equals(resBean.getCode())) {
					JSONObject jsonObj = resBean.getData();
					JSONArray arr = JSON.parseArray(String.valueOf(jsonObj.get("list")));

					if (CollectionUtils.isNotEmpty(arr)) {
						for (Object obj : arr) {
							JSONObject jsonObject = (JSONObject) obj;

							TtAppManagement management = new TtAppManagement();
							management.setAdvertiserId(advertiserId);
							management.setPackageId(jsonObject.getString("package_id"));
							management.setPackageName(jsonObject.getString("package_name"));
							management.setAppCloudId(jsonObject.getString("app_cloud_id"));
							management.setAppName(jsonObject.getString("app_name"));
							management.setVersion(jsonObject.getString("version"));
							management.setDownloadUrl(jsonObject.getString("download_url"));
							management.setPublishTime(jsonObject.getDate("publish_time"));
							management.setSearchType(searchType);
							management.setCreateTime(new Date());
							management.setUpdateTime(new Date());
							appManagementList.add(management);
						}
					}

					JSONObject pageInfo = (JSONObject) jsonObj.get("page_info");
					int totalPage = pageInfo.getInteger("total_page");
					if (page >= totalPage) {
						break;
					}
					page++;
				} else {
					log.info(">>>应用信息APPID广告账户：{}，拉取失败，原因：{}", advertiserId, resBean.getMessage());
					XxlJobLogger.log(">>>应用信息APPID广告账户：{}，拉取失败，原因：{}", advertiserId, resBean.getMessage());
					break;
				}
			} catch (Exception e) {
				e.printStackTrace();
				break;
			}
		}
		return appManagementList;
	}

	/**
	 * 通过 appid 查询对应的广告账户和应用分包id
	 *
	 * @param appId
	 * @return
	 */
	@Override
	public TtAppManagement getPackageIdByAppId(String appId) {
		TtAppManagement one = this.getOne(Wrappers.<TtAppManagement>query()
				.lambda().eq(TtAppManagement::getAppCloudId, appId).eq(TtAppManagement::getIsDeleted, 0).last("LIMIT 1"));
		return one;
	}

/*	public static void main(String[] args) {
		String url = "https://ad.oceanengine.com/open_api/2/tools/app_management/app/get/";
		String advertiserId = "1670991347555336";
		//公共方法获取accessToken
//		String accessToken = ttAccesstokenService.fetchAccesstoken(advertiserId);
		String accessToken = "6ed04d7cdadedf7ce0740e80052f67b942400c8c";
		Map<String, Object> data = new HashMap<String, Object>();
		data.put("advertiser_id", advertiserId);
		//调第三方平台（头条）接口
		String resultStr = OEHttpUtils.doGet(url, data, accessToken);
		System.out.println(">>>>>>1" + resultStr);
		ResponseBean resBean = JSON.parseObject(resultStr, ResponseBean.class);
		System.out.println(">>>>>>2" + JSON.toJSONString(resBean));
	}*/
}
